package cn.momoky.ccool.service;

import cn.momoky.ccool.exception.GlobalException;
import cn.momoky.ccool.pojo.User;
import cn.momoky.ccool.pojo.view.LoginRequest;
import cn.momoky.ccool.pojo.view.LoginResponse;
import cn.momoky.ccool.repository.UserRepository;
import cn.momoky.ccool.util.JwtUtil;
import cn.momoky.ccool.utils.ResultStatus;
import cn.momoky.ccool.utils.WebUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Service
@AllArgsConstructor
public class UserService {


    private final UserRepository userRepository;

    public LoginResponse login(LoginRequest loginRequest){
        HttpServletRequest request = WebUtils.getRequest();

        User userLogin = userRepository.verificationUser(loginRequest.getName());
        if (null == userLogin) {
            log.info("{}用户不存在",loginRequest.getName());
            throw new GlobalException(ResultStatus.NOT_FOUND_USER.getCode(), ResultStatus.NOT_FOUND_USER.getMsg());
        }
        if (!userLogin.getPassword().equals(loginRequest.getPassword())) {
            log.info("登录用户：{} 密码错误：{}", loginRequest.getName(),loginRequest.getPassword());
            throw new GlobalException(ResultStatus.PASSWORD_ERROR.getCode(), ResultStatus.PASSWORD_ERROR.getMsg());
        }
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>> " + WebUtils.getHost());
        String tokenStr = JwtUtil.getJwtToken(userLogin.getId().toString(), userLogin.getName(), WebUtils.getHost(), null,null);
        return new LoginResponse().setToken(tokenStr);
    }
}
